package cmich.cps.svn.hooks;

import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.MemoryHandler;
import java.util.logging.SimpleFormatter;
/**
 * Uses java.logging.util
 * 
 * @author Jonathan Kissinger <kissi1j@cmich.edu>
 *
 */
public class MyLogger {
	/**
	 * True if log records should be logged, otherwise false
	 */
	private static Boolean logging = false;
	/**
	 * Contains 2 handlers, a memory handler and a console handler.
	 * 
	 * @param trigger The level at which the memory handler will write to a file
	 * @param level  Records below this level are ignored, standard handler level
	 * @param path  Parent path for the log file
	 */
	static public void setup(final Level trigger, Level level, String path) {
		String basePackage = MyLogger.class.getPackage().getName().split("\\.")[0];
		Logger logger = Logger.getLogger(basePackage);
		logger.setLevel(level);
		try {
			SimpleFormatter simple = new SimpleFormatter();
			if(trigger.intValue()>Level.FINEST.intValue()) {
				FileHandler logFile = new FileHandler(path + "/testing/Log.txt", 524288, 10, true);
				logFile.setFormatter(simple);
				int numRec = 100;
				MemoryHandler logMemory = new MemoryHandler(logFile, numRec, Level.OFF) {
					public synchronized void publish(LogRecord record) {
						super.publish(record);
						if(record.getLevel().intValue()>=trigger.intValue()) {
							logging = true;
						}
						if(logging) {
							push();
						}		            
					}
				};
				logMemory.setFormatter(simple);
				logger.addHandler(logMemory);
			}
			else {
				//Prevents info and higher from printing to the screen twice
				Logger.getLogger("").getHandlers()[0].setLevel(Level.OFF);
				
				ConsoleHandler console = new ConsoleHandler();
				console.setFormatter(simple);
				console.setLevel(Level.FINEST);
				logger.addHandler(console);
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
